package tk.uodrad.apex.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import tk.uodrad.apex.project.ex.ServiceException;
import tk.uodrad.apex.project.pojo.dto.UserLoginDTO;
import tk.uodrad.apex.project.pojo.entity.User;
import tk.uodrad.apex.project.pojo.vo.UserInfoVO;
import tk.uodrad.apex.project.service.UserService;
import tk.uodrad.apex.project.mapper.UserMapper;
import org.springframework.stereotype.Service;
import tk.uodrad.apex.project.web.ServiceCode;

import java.util.Date;

/**
* @author Administrator
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-04-10 15:46:11
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret_key}")
    private String secret_key;

    @Value("${jwt.expiration_time}")
    private Long expiration_time;

    /**
     * 登录
     * @param userLoginDTO 用户登录DTO
     */
    @Override
    public String login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        // 使用MD5加密密码
        String passwordMd5 = DigestUtils.md5Hex(userLoginDTO.getPassword());
        // 根据用户名查询已存在用户
        QueryWrapper<User> queryWrapper = Wrappers.query();
        queryWrapper.eq("username", username);
        User selectUser = userMapper.selectOne(queryWrapper);
        // 判断该用户是否存在或者密码是否正确
        if (selectUser == null || !selectUser.getPassword().equals(passwordMd5)) {
            String message = "登录失败，用户名或密码错误！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UNAUTHENTICATED, message);
        }
        // 创建user对象并更新最后登录时间
        User user = new User();
        user.setLoginTime(new Date());
        int rows = userMapper.update(user, queryWrapper);
        if (rows != 1) {
            String message = "服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        // 生成Token
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + expiration_time * 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, secret_key)
                .compact();
    }

    @Override
    public UserInfoVO checkJwt(String jwt) {
        try {
            String username = Jwts.parser().setSigningKey(secret_key).parseClaimsJws(jwt).getBody().getSubject();
            QueryWrapper<User> queryWrapper = Wrappers.query();
            queryWrapper.eq("username", username);
            User selectUser = userMapper.selectOne(queryWrapper);
            if (selectUser == null) {
                String message = "非法访问，请正确登录！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, message);
            }
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(selectUser, userInfoVO);
            return userInfoVO;
        } catch (Exception e) {
            String message = "非法访问，请正确登录！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, message);
        }
    }
}




